<template>
  <div class="page-list-live">
    <PageList>
      <template #header>考勤统计</template>
      <!-- 表单搜索 -->
      <template #filter>
        <ListFilter :form="topFilter" @search="handleSearch" @changItemHandler="changItemHandler" @reset="handleReset"></ListFilter>
      </template>
      <!-- 按钮 -->
      <template #tips>
        <el-button icon="el-icon-delete" type="danger" @click="batchDeletion">批量删除</el-button>
        <el-button icon="el-icon-document-add" type="primary" @click="handleAdd">补录</el-button>
      </template>
      <!-- 表格 -->
      <template #table>
        <ListTable
          ref="RefListTable"
          :loading="tableLoading"
          :table-data="tableData"
          :table-col="tableCol"
          :enter-time-start="EnterTimeStart"
          :enter-time-end="EnterTimeEnd"
          @size-change="sizeChange"
          @selectChange="handleSelectionChange"
        >
          <template slot="col1" slot-scope="scope">
            <el-button icon="el-icon-s-release" :loading="scope.row.loadingEdit" size="mini" type="text" @click="handleRowDetails(scope.row)">详情</el-button>
            <el-button :loading="scope.row.loadingDel" size="mini" icon="el-icon-delete" style="color: red;" type="text" @click="handleRowDel(scope.row)">删除</el-button>
          </template>
        </ListTable>
      </template>
    </PageList>
    <addAttendance ref="addAttendance"></addAttendance>
    <detailsAttendance ref="detailsAttendance" @success="afterEditSuccess"></detailsAttendance>
  </div>
</template>
<script>
  import listMixin from '@/mixins/list'
  import addAttendance from './components/addEditAttendance'
  import detailsAttendance from './components/detailsAttendance.vue'
  import ListFilter from '@/components/ListFilter'
  import { department, job, work, attendanceList } from '@/api/api'
  export default {
    components: {
      ListFilter,
      addAttendance,
      detailsAttendance
    },
    mixins: [listMixin],
    data() {
      return {
        EnterTimeStart: (function () {
          var d = new Date()
          return d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate()
        }()),
        EnterTimeEnd: (function () {
          var d = new Date() * 1
          var t = new Date(d + 24 * 60 * 60 * 1000)

          return t.getFullYear() + "-" + (t.getMonth() + 1) + "-" + t.getDate()
        }()),
        deleteList: {
          id: ''
        },
        pageIndex: 1,
        topFilter: {

        },
        // 部门数据
        dptList: [],
        // 职位数据
        jobList: [],
        // 工种数据
        workList: [],
        tableData: [],
        tableCol: [
          { type: 'selection' },
          { prop: 'code', label: '员工编号' },
          { prop: 'name', label: '员工名称' },
          { prop: 'rfid', label: 'RFID卡号' },
          { prop: 'accessCardID', label: '门禁卡号' },
          { prop: 'departmentName', label: '部门' },
          { prop: 'jobName', label: '职位' },
          { prop: 'workType', label: '工种' },
          { prop: 'entertime', label: '进场时间' },
          { prop: 'leaveTime', label: '出场时间' },
          { prop: 'enterCount', label: '进洞次数' },
          { prop: 'attendanceType', label: '考勤方式' },
          { prop: 'totalWorkHours', label: '累计工时' },
          { label: '操作', custom: 'col1' }
        ]
      }
    },
    mounted() {
      // 获取下拉框数据并赋值给查询组件
      this.threeList(() => {
        this.topFilter = {
          DepartmentId: { label: '部门', placeholder: '请选择部门', type: 'select', arr: this.dptList },
          JobId: { label: '职位', placeholder: '请选择职位', type: 'select', arr: this.jobList },
          WorkType: { label: '工种', placeholder: '请选择工种', type: 'select', arr: this.workList },
          Name: { label: '员工名称', placeholder: '请输入员工名称' },
          RFID: { label: 'RFID卡', placeholder: '请输入RFID卡' },
          DoorId: { label: '门禁ID', placeholder: '请输入门禁ID' },
          enterTime: { label: '进入隧道时间', type: 'date', arr: ['EnterTimeStart', 'EnterTimeEnd'] }
        }
      })
      this.$store.dispatch('user/setAttendanceDate', { EnterTimeStart: this.EnterTimeStart, EnterTimeEnd: this.EnterTimeEnd, status: true })
    },
    beforeDestroy() {
      this.$store.dispatch('user/setAttendanceDate', { EnterTimeStart: null, EnterTimeEnd: null, status: false })
    },
    methods: {
      async changItemHandler(obj) {
        if (!obj.val) {
          return
        } else if (obj.key === "DepartmentId") {
          try {
            let ob = { pageIndex: 1, pageSize: 1e8 }
            let result = await job("post", ob, false)
            this.arr = []
            result.data.items.forEach(item => {
              if (item.department.id == obj.val) {
                this.arr.push({
                  label: item.jobTitle,
                  value: item.id,
                })
              }
            })
            console.log(this.arr)
            this.topFilter.JobId.arr = this.arr
          } catch (err) {
            console.log(err)
          }
        } else if (obj.key == "enterTime" && obj.val[0]) {
          this.EnterTimeStart = obj.val[0]
          this.EnterTimeEnd = obj.val[1]
        }
      },
      sizeChange(obj) {
        // console.log(obj)
      },
      handleSearch(obj) {
        let arr = obj.search.map(item => {
          return Object.values(item).map(val => {
            return val
          })
        })
        arr.forEach(item => {
          obj[item[0]] = item[1]
        })
        delete obj.search
        this.getList({ ...obj, pageSize: 10 })
      },
      // 批量删除
      batchDeletion() {
        this.$_delConfirm('部门', () => {
          this.delRowReq(this.deleteList)
        })
      },
      // 选中事件
      handleSelectionChange(event) {
        if (event.length > 0) {
          let ary = []
          event.forEach(item => {
            ary.push(item.id)
          })
          if (ary.length > 1) {
            this.deleteList.id = ary.join(',')
          } else {
            this.deleteList.id = ary[0]
          }
        } else {
          this.deleteList.id = ''
        }
      },
      // 查询部门，职位，工种
      async threeList(fn) {
        try {
          let obj = { pageIndex: this.pageIndex }
          let resList = await Promise.all([department('post', obj, false), job('post', obj, false), work('post', obj, false)])
          // 部门
          if (resList[0].code === 200) {
            this.dptList = resList[0].data.items.map(item => {
              if (item.lenght === 0) { return }
              return {
                label: item.deptName,
                value: item.id
              }
            })
          }
          // 职位
          if (resList[1].code === 200) {
            this.jobList = resList[1].data.items.map(item => {
              if (item.lenght === 0) { return }
              return {
                label: item.jobTitle,
                value: item.id,
                department: item.department
              }
            })
          }
          // 工种
          if (resList[2].code === 200) {
            this.workList = resList[2].data.items.map(item => {
              if (item.lenght === 0) { return }
              return {
                label: item.workName,
                value: item.id
              }
            })
          }
        } catch (err) {
          console.log(err)
        }
        fn()
      },
      // 请求列表数据
      async getList(query) {
        this.tableLoading = true
        try {
          let obj = query || {
            orderBy: "createdTime",
            orderByAscent: false,
            EnterTimeStart: this.EnterTimeStart,
            EnterTimeEnd: this.EnterTimeEnd,
            pageIndex: this.pageIndex,
            pageSize: 10
          }
          const { result, total } = await attendanceList('get', obj, false)

          let pageIndex = query ? query.pageIndex : this.pageIndex
          this.tableData = result
          this.$nextTick(() => {
            this.$refs['RefListTable'].update({ page: Number(pageIndex), count: total })
            this.tableLoading = false
          })
        } catch (err) {
          this.tableLoading = false
          console.error('getList err: ', err)
        }
      },
      async afterEditSuccess() {
        await this.$router.push({ query: {} })
        this.getList()
      },
      // 新增
      handleAdd() {
        this.$refs['addAttendance'].open()
        this.$refs['addAttendance'].getDepartmentList()
      },
      // 详情
      handleRowDetails(row) {
        this.$refs['detailsAttendance'].open(row, true, true, { start: this.EnterTimeStart, end: this.EnterTimeEnd })
      },
      async delRowReq(row) {
        try {
          await this.$api['department/delete'](
            {},
            { apiParams: { id: row.id } }
          )
          row.loadingDel = false
          await this.$router.push({ query: {} })
          this.getList()
          this.$message({
            type: 'success',
            message: '删除成功'
          })
        } catch (err) {
          row.loadingDel = false
          this.$message({
            type: 'error',
            message: '删除失败'
          })
          console.error('handleRowDel err: ', err)
        }
      },
      handleRowDel(row) {
        row.loadingDel = true
        this.$_delConfirm(
          '部门',
          () => {
            this.delRowReq(row)
          },
          () => {
            row.loadingDel = false
          }
        )
      }
    }
  }
</script>

<style lang="scss" scoped></style>
